package com.hualan.servlet;

import com.alibaba.fastjson.JSON;
import com.hualan.bean.PanghuShop;
import com.hualan.dao.StoreDaoAdd;
import com.hualan.dao.impl.StoreDaoAddImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/store/update")
public class StoreUpdateServlet extends HttpServlet {
    //GET 用于通过id获取要编辑的门店对象

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("shopId"));
        StoreDaoAdd storeDaoAdd = new StoreDaoAddImpl();
        PanghuShop shop = storeDaoAdd.selectById(id);
        //解析接收的中文
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        Map<String, Object> map = new HashMap<>();
        if (shop == null){
            map.put("code", 300);
            map.put("message", "id不合法!");
        }else {
            map.put("code", 200);
            map.put("message", "获取成功");
            map.put("data", shop);
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }


    //POST  用于提交编辑信息到数据库
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解析中文
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //请求数据

        String name = req.getParameter("shopName");
        String describe = req.getParameter("shopDescribe");
        String image = req.getParameter("shopImage");
        String phone = req.getParameter("shopPhone");
        String province = req.getParameter("shopProvince");
        String city = req.getParameter("shopCity");
        String district = req.getParameter("shopDistrict");
        String address = req.getParameter("shopAddress");
        String longitude = req.getParameter("shopLongitude");
        String latitude = req.getParameter("shopLatitude");
        int id = Integer.parseInt(req.getParameter("shopId"));
//        System.out.println("后端获取的id:"  + id);
        //封装shop对象
        PanghuShop shop = new PanghuShop(id,name,describe,image,phone,province,city,district,address,longitude,latitude);
        //创捷接口(多态)对象
//        System.out.println("servlet中的shopid:"  + shop.getShopId());
        StoreDaoAdd storeDaoAdd = new StoreDaoAddImpl();
        int row = storeDaoAdd.update(shop);
        //创建map对象存储数据
        Map<String,Object> map = new HashMap<>();
        if (row > 0){
            map.put("code", 200); //更新成功
        }else {
            map.put("code", 300);
        }
        resp.getWriter().write(JSON.toJSONString(map));
    }
}
